package com.example.stream;

import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.LongStream;
//010
public class TestForkJoin {

    private static final long count = 50000000000L;

    //ForkJoin框架
    @Test
    public void test1() {
        Instant start = Instant.now();
        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinCalculate task = new ForkJoinCalculate(0, count);
        Long sum = pool.invoke(task);
        System.out.println(sum);

        Instant end = Instant.now();
        System.out.println("JOIN-" + Duration.between(start, end).toMillis());
    }

    @Test
    public void test2() {
        Instant start = Instant.now();
        long sum = 0L;
        for (long i = 0; i < count; i++) {
            sum += i;
        }
        System.out.println(sum);
        Instant end = Instant.now();
        System.out.println("NOR-" + Duration.between(start, end).toMillis());
    }

    //java8并行流
    @Test
    public void test3() {
        Instant start = Instant.now();
        long reduce = LongStream.rangeClosed(0, count)
                .parallel()
                .reduce(0, Long::sum);
        System.out.println(reduce);
        Instant end = Instant.now();
        System.out.println("PARALLEL-" + Duration.between(start, end).toMillis());
    }
}
